package com.czh.seckill.rabbitMQ;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czh.seckill.pojo.SeckillMessage;
import com.czh.seckill.pojo.SeckillOrder;
import com.czh.seckill.pojo.User;
import com.czh.seckill.service.IGoodsService;
import com.czh.seckill.service.IOrderService;
import com.czh.seckill.vo.GoodsVo;
import com.czh.seckill.vo.RespBean;
import com.czh.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;

@Slf4j
@Service
public class MQReceiver {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    //下单
    @RabbitListener(queues = "seckillQueue")
    public void receiveMessage(String message) {
        log.info("接收的消息" + message);
        SeckillMessage seckillMessage = JSON.parseObject(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购(再次判断)
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return;
        }
        //下单操作
        try {
            orderService.seckill(user, goodsVo);
        } catch (Exception e) {
            return;
        }
        return;


//    @RabbitListener(queues = "queue")
//    public void receive(Object msg) {
//        log.info("接受消息:" + msg);
//    }
//
////    @RabbitListener(queues = "queue_fanout01")
////    public void receive01(Object msg) {
////        log.info("01接受消息:" + msg);
////    }
////
////    @RabbitListener(queues = "queue_fanout02")
////    public void receive02(Object msg) {
////        log.info("02接受消息:" + msg);
////    }
//
//    @RabbitListener(queues = "queue_topic01")
//    public void receive01(Object msg) {
//        log.info("01接受消息:" + msg);
//    }
//
//    @RabbitListener(queues = "queue_topic02")
//    public void receive02(Object msg) {
//        log.info("02接受消息:" + msg);
//    }
    }
}
